package week03.single;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by zhangxiaokun on 2018/2/8.
 */
public class TestSingleton {
    public static void main(String[] args) {
//        Singleton01.axx();
//        Singleton01 instance = Singleton01.getInstance();
//        System.out.println(instance);
//        System.out.println(instance == Singleton01.getInstance());

//        Singleton02.axx();
//        Singleton02 instanceS2 = Singleton02.getInstance();
//        System.out.println(Singleton02.getInstance() == Singleton02.getInstance());

//        Singleton03.axx();
//        Singleton03.getInstance();

//        Singleton04.axx();
//        MySingleton bean = Singleton04.getInstance();
//        System.out.println(bean);

        //绕过单例限制(private 限制)，获得多个实例
        testGetMoreInstance();
    }

    //通过反射绕开 单例限制(private 构造器限制)，获取多个实例
    private static void testGetMoreInstance() {
        try {
            //单例模式 通过Singleton01 提供的方法获取实例
            Singleton01 instance01 = Singleton01.getInstance();
            instance01.setId(1);
            System.out.println("instance01:" + instance01 + "\tid:" + instance01.getId() + "\tname:" + instance01.getName());

            Class clazz = Class.forName("week03.single.Singleton01");
            Constructor<Singleton01> constructor = clazz.getDeclaredConstructor();
            constructor.setAccessible(true);
            Singleton01 instance02 = constructor.newInstance();
            instance02.setId(2);
            Singleton01.name = "bb";

            System.out.println("instance02:" + instance02 + "\tid:" + instance02.getId() + "\tname:" + instance02.getName());
            System.out.println("instance01:" + instance01 + "\tid:" + instance01.getId() + "\tname:" + instance01.getName());
            System.out.println(instance01 == instance02);

            System.out.println(Singleton01.getInstance());
            System.out.println(instance02);
            System.out.println(Singleton01.getInstance());
            System.out.println(Singleton01.getInstance());

        } catch (ClassNotFoundException |
                NoSuchMethodException |
                IllegalAccessException |
                InstantiationException |
                InvocationTargetException  e) {
            e.printStackTrace();
        }
    }
}

